using Devonline.Core;
using Devonline.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Devonline.MessageCenter
{
    public class Startup
    {
        public IWebHostEnvironment Environment { get; }
        public IConfiguration Configuration { get; }

        public Startup(IWebHostEnvironment environment, IConfiguration configuration)
        {
            Environment = environment;
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var appSetting = services.AddAppSettings<McSetting>();

            services.AddLogging();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllers().AddJsonOptions();
            services.AddStackExchangeRedisCache(options => options.Configuration = appSetting.Redis);

            services.AddResponseCompression();
            services.AddSignalR()
                .AddNewtonsoftJsonProtocol(config => config.PayloadSerializerSettings = AppSettings.JsonSerializerSettings)
                .AddStackExchangeRedis(appSetting.Redis);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseResponseCompression();

            var appSetting = app.ApplicationServices.GetService<McSetting>();

            app.UseEndpoints(endpoints =>
            {
                if (!string.IsNullOrEmpty(appSetting.HubEndpint))
                {
                    endpoints.MapHub<TextMessageHub>(appSetting.HubEndpint, options => { options.Transports = HttpTransportType.WebSockets | HttpTransportType.LongPolling; });
                }
            });
        }
    }
}
